package com.example.friend.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;
import java.util.Arrays;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


import com.example.friend.dao.UserDAO;
import com.example.friend.pojo.User;

@WebServlet("/register")
public class RegisterServlet extends HttpServlet{

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
	
		// 设定编码
		req.setCharacterEncoding("utf-8");
		resp.setContentType("text/html;charset=utf-8");
		
		String username = req.getParameter("username");
		String password = req.getParameter("password");
		String gender = req.getParameter("gender");
		String[] status = req.getParameterValues("status");
		String birthday = req.getParameter("birthday");	
		String tel = req.getParameter("tel");
		String qq = req.getParameter("qq");
		
		String ageStr = req.getParameter("age");
		int age = Integer.parseInt(ageStr);
		
		String[] likes = req.getParameterValues("likes");
		String[] edu = req.getParameterValues("edu");				
		String intro = req.getParameter("intro");
		
		PrintWriter pw = resp.getWriter();
		pw.print(username+"<br />");
		pw.print(password+"<br />");
		pw.print(gender+"<br />");
		pw.print(tel+"<br />");
		pw.print(qq+"<br />");
		pw.print(age+"<br />");
		pw.print(Arrays.toString(edu)+"<br />");
		pw.print(Arrays.toString(status)+"<br />");
		pw.print(birthday+"<br />");
		pw.print(Arrays.toString(likes)+"<br />");
		pw.print(intro+"<br />");
		
		// 把用户信息放入一个User对象中
		User u = new User();
		u.setUsername(username);
		u.setPassword(password);
		u.setGender(gender);
		u.setTel(tel);
		u.setQq(qq);
		u.setAge(age);
		u.setBirthday(birthday);
		u.setIntro(intro);
		
		//学历
		String eduStr = "";
		for(int i=0;i<edu.length;i++) {
			eduStr += edu[i];
		}
		u.setEdu(eduStr);
		
		//婚姻状况
		String statusStr = "";
		for(int i=0;i<status.length;i++) {
			statusStr += status[i];
		}
		u.setStatus(statusStr);
		
		// 打球,下棋,打游戏
		String likesStr = "";
		for(int i=0;i<likes.length;i++){
			likesStr += likes[i]+",";
		}
			u.setLikes(likesStr);
				
		// 调用 DAO 实现注册
		UserDAO dao = new UserDAO();
		int result = 0;
		try {
			result = dao.insert(u);
		} catch (SQLException e) {
		// TODO Auto-generated catch block
			e.printStackTrace();
		}
				
				// 根据注册结果显示
		if(result==1){
			pw.print("<h1>注册成功</h1>");
		}else{
			pw.print("<h1>注册失败</h1>");
			}
		}
	
		@Override
		protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
				doGet(req,resp);
			}
		}